<template>
  <div>
    <div ref="chart" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import moment from 'moment';
  import { CollectDataQuery,CollectDataQueryNew } from '@/api/system/datamanage';
  import resize from './mixins/resize';

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      autoResize: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        chart: null,
        ylTimes: [], // 保存时间
        ylValuesOne: [], // 保存对应时间的数据
        ylValuesTwo: [],
        intervalId: null, // 定时器ID
        isInitialized: false, // 是否已经找到匹配数据
        form: {
          startTime: '',
          endTime: '',
          sectionNo: '',
          pageSize: 1,
          pageNum: 1
        }
      };
    },
    mounted() {
      this.initChart();
      // this.initializeData();
    },
    deactivated() {
      if (this.chart) {
        this.chart.dispose();
      }
      clearInterval(this.intervalId); // 清除定时器
      this.intervalId = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$refs.chart);
        const option = {
          title: {
            text: '压力值'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.ylTimes
          },
          yAxis: {
            type: 'value'
          },
          graphic: {
            type: 'text',     // 类型：文本
            left: 'center',
            top: 'middle',
            silent: true,     // 不响应事件
            invisible: this.ylValuesOne.length > 0 || this.ylValuesTwo.length > 0,   // 有数据就隐藏
            style: {
              fill: '#9d9d9d',
              fontWeight: 'bold',
              text: '暂无数据',
              fontFamily: 'Microsoft YaHei',
              fontSize: '25px'
            }
          },
          series: [
            {
              name: '压力值1',
              type: 'line',
              data: this.ylValuesOne
            },
            {
              name: '压力值2',
              type: 'line',
              data: this.ylValuesTwo
            }
          ]
        };
        this.chart.setOption(option);
      },
      async initializeData() {

        while (!this.isInitialized) {
          try {
            const currentTime = new Date(); // 当前时间
            this.form.startTime = this.parseTime(currentTime.getTime() - 1000); // 当前时间减一秒
            this.form.endTime = this.parseTime(currentTime.getTime() + 1000); // 当前时间加一秒

            const res = await CollectDataQueryNew(this.form);
            const response = JSON.parse(res);
            if (response.length > 0) {
              const {time, createTime, MeasurPressOne, MeasurPressTwo } = response[0];

              // 将UTC时间转换为本地时间并格式化
              const formattedTime = moment.utc(createTime).local().format('HH:mm:ss');

              if (formattedTime === currentTime) {
                // 找到匹配的数据
                this.isInitialized = true;
                // this.ylTimes.push(formattedTime);
                // this.ylValuesOne.push(MeasurPressOne);
                // this.ylValuesTwo.push(MeasurPressTwo);
                // this.njTimes = time.length<=0?[this.njForm.startTime.slice(11, 19),this.njForm.endTime.slice(11, 19)]:time
                this.ylTimes = time.length<=0?[this.njForm.startTime.slice(11, 19),this.njForm.endTime.slice(11, 19)]:time
                this.njValues = currentMaximumMoment.length<=0?['0','0']:currentMaximumMoment
                this.ylValuesOne = maximumWorkingMoment1.length<=0?['0','0']:maximumWorkingMoment1
                this.ylValuesTwo = maximumWorkingMoment2.length<=0?['0','0']:maximumWorkingMoment2

                // 更新图表
                this.chart.setOption({
                  xAxis: {
                    data: this.ylTimes
                  },
                  series: [
                    {
                      name: '压力值1',
                      type: 'line',
                      data: this.ylValuesOne
                    },
                    {
                      name: '压力值2',
                      type: 'line',
                      data: this.ylValuesTwo
                    }
                  ]
                });

                // 开始定时请求
                this.startInterval();
              }
            }

          } catch (error) {
            console.error('Error fetching data:', error);
          }

          // 等待一段时间后再次尝试
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      },
      async updateData() {
        try {
          const currentTime = new Date(); // 当前时间
          this.form.startTime = this.parseTime(currentTime.getTime() - 1000); // 当前时间减一秒
          this.form.endTime = this.parseTime(currentTime.getTime() + 1000); // 当前时间加一秒
          const response = await CollectDataQueryNew(this.form);
          const {time, createTime, MeasurPressOne, MeasurPressTwo } = response.data;

          // 将UTC时间转换为本地时间并格式化
          const formattedTime = moment.utc(createTime).local().format('HH:mm:ss');

          // 如果数组已满，移除最早的一个时间数据
          // if (this.ylTimes.length >= 5) {
          //   this.ylTimes.shift();
          //   this.ylValuesOne.shift();
          //   this.ylValuesTwo.shift();

          // }

          // 添加新的时间和数据
          // this.ylTimes.push(formattedTime);
          // this.ylValuesOne.push(MeasurPressOne);
          // this.ylValuesTwo.push(MeasurPressTwo);
          // this.njTimes = time.length<=0?[this.njForm.startTime.slice(11, 19),this.njForm.endTime.slice(11, 19)]:time
          this.ylTimes = time.length<=0?[this.form.startTime.slice(11, 19),this.form.endTime.slice(11, 19)]:time
          this.njValues = currentMaximumMoment.length<=0?['0','0']:currentMaximumMoment
          this.ylValuesOne = maximumWorkingMoment1.length<=0?['0','0']:maximumWorkingMoment1
          this.ylValuesTwo = maximumWorkingMoment2.length<=0?['0','0']:maximumWorkingMoment2

          // 更新图表
          this.chart.setOption({
            xAxis: {
              data: this.ylTimes
            },
            series: [
              {
                name: '压力值1',
                type: 'line',
                data: this.ylValuesOne
              },
              {
                name: '压力值2',
                type: 'line',
                data: this.ylValuesTwo
              }
            ]
          });
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      },
      startInterval() {
        this.intervalId = setInterval(this.updateData, 3 * 1000); // 每3秒更新一次
      }
    }
  };
</script>

<style scoped>
  /* 样式可以根据需要自定义 */
</style>
